<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>{{ $route.query.type == "add" ? '新建市级宣讲队' : "编辑市级宣讲队" }}</span>
        <el-button type="primary" :loading="buttonLoading" @click="goList">退出</el-button>
      </div>
    </template>

    <div class="add-form" v-loading="loading">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="宣讲队名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入宣讲队名称" clearable></el-input>
        </el-form-item>

        <el-form-item label="责任单位" prop="responsibleUnit">
          <el-input v-model="ruleForm.responsibleUnit" placeholder="请输入责任单位" clearable></el-input>
        </el-form-item>

        <el-form-item label="经度" prop="longitude">
          <el-input v-model="ruleForm.longitude" placeholder="请输入宣讲队责任单位所处经度"></el-input>
        </el-form-item>

        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="ruleForm.latitude" placeholder="请输入宣讲队责任单位所处纬度"></el-input>
        </el-form-item>

        <el-form-item label="区划" prop="area">
          <el-input v-model="ruleForm.area" placeholder="请输入宣讲队责任单位所属行政区划，例如：洪山区"></el-input>
        </el-form-item>

        <el-form-item label="成员情况" prop="memberShip">
          <el-input v-model="ruleForm.memberShip" placeholder="请输入成员情况"></el-input>
        </el-form-item>

        <el-form-item label="宣讲对象" prop="preachObject">
          <el-input v-model="ruleForm.preachObject" placeholder="请输入宣讲对象"></el-input>
        </el-form-item>

        <el-form-item label="成立时间" prop="creationTime">
          <el-date-picker
            v-model="ruleForm.creationTime"
            type="date"
            placeholder="请选择成立时间"
            value-format="YYYY-MM-DD"
            clearable
          />
        </el-form-item>

        <el-form-item label="封面图片" prop="coverUrl">
          <el-image style="width: 313px;"
            :src="imageUrl ? imageUrl : ''" fit="cover">
            <template #error>
              <div class="image-slot">
                <el-image style="width: 313px;" src="/images/course_default.png" fit="cover" />
              </div>
            </template>
          </el-image>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="uploadEvent">
            <el-icon>
              <UploadFilled />
            </el-icon>
            上传封面图片
          </el-button>
          <span style="margin-left: 10px;">请上传不超过10M的图片，格式：jpg/png/jpeg</span>
        </el-form-item>
        
        <el-form-item class="add-button">
          <el-button type="primary" @click="submitForm(ruleFormRef)" :loading="buttonLoading">
            {{ $route.query.type == "add" ? '新增' : "编辑" }}
          </el-button>
          <el-button @click="resetForm(ruleFormRef)" :loading="buttonLoading">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script>
export default { name: "backendPublicizeCityAdd" }
</script>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router'
import { UploadFilled, Picture } from '@element-plus/icons-vue'
import tEditor from "@/components/tinymceEditor/tEditor.vue"
import { ElMessage } from 'element-plus'
import { http } from '@/utils/http/index';
import { uploadFile } from '@/utils/file.js'
import { format } from '@/plugins/moment.js'
import { testFileType, testFileSize } from '@/utils/backend.js'
import { ContentTypeEnum } from '@/enums/httpEnum';

/* 路由 */
const route = useRouter()

onMounted(() => {
  if(route.currentRoute.value.query.id){
    getCityDetail()
  }
})

/* 详情数据加载动画 */
const loading = ref(false)

/* 查询详情 */
const getCityDetail = () => {
  loading.value = true
  http.$GET("/PreachM/GetPreachTeamDetailById", { Id: route.currentRoute.value.query.id }).then(res => {
    loading.value = false
    if (res.isError) return
    if (!res.result) return
    
    /* 赋值 */
    Object.keys(ruleForm.value).forEach((key)=>{
      if(res.result[key] != null){
        ruleForm.value[key] = res.result[key];
      }
    })

    /* 处理成立时间 */
    ruleForm.value.creationTime = format(res.result.creationTime)

    /* 封面图片路径 */
    if(res.result.coverUrl != ''){
      let picture = JSON.parse(res.result.coverUrl)

      if(picture.filePathArray){
        imageUrl.value = import.meta.env.VITE_APP_STATIC_URL + picture.filePathArray[0].CompleteFilePath
      }else{
        imageUrl.value = ""
        ruleForm.value.coverUrl = ""
      }
    }
  }).catch(err => {
    loading.value = false
    ElMessage.warning("查询失败")
  })
}

/* 新增、编辑表单 */
const ruleFormRef = ref(null)

/* 新增、编辑表单数据 */
const ruleForm = ref({
  id: "",
  name: "",
  responsibleUnit: "",
  memberShip: "",
  preachObject: "",
  coverUrl: "",
  creationTime: "",
  longitude: "",
  latitude: "",
  area: "",
})

/* 封面图片路径 */
const imageUrl = ref(null)
/* 是否有上传图片 */
const isUploadImage = ref(false)

/* 封面图片校验规则 */
const checkFile = (rule, value, callback) => {
  if (!ruleForm.value.coverUrl) {
    callback(new Error('请上传封面图片'))
  } else {
    callback()
  }
}

/* 表单校验规则 */
const rules = reactive({
  name: [
    { required: true, message: '请填写宣讲队名称', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  responsibleUnit: [
    { required: true, message: '请填写责任单位', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  preachObject: [
    { required: true, message: '请填写宣讲对象', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  memberShip: [
    { required: true, message: '请填写成员情况', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  creationTime: [
    { required: true, message: '请选择成立时间', trigger: 'change' }
  ],
  longitude: [
    { required: true, message: '请填写宣讲队责任单位所处经度', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  latitude: [
    { required: true, message: '请填写宣讲队责任单位所处纬度', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  area: [
    { required: true, message: '请填写宣讲队责任单位所属行政区划，例如：洪山区', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  /* coverUrl: [
    { required: true, validator: checkFile, message: '请上传封面图片', trigger: 'change' }
  ], */
})

/* 点击上传文件 */
const uploadEvent = () => {

  /* 文件上传类型 */
  let fileType = ".jpg,.jpeg,.png,.JPG,.JPEG,.PNG"

  uploadFile({ accept: fileType }).then(res => {
    /* 文件格式判断 */
    if(!testFileType(res, /^(jpg|jpeg|png|JPG|JPEG|PNG)$/)){
      ruleForm.value.coverUrl = ""
      imageUrl.value = ""
      isUploadImage.value = false
      return 
    }
    /* 文件大小判断 */
    if(!testFileSize(res, 10*1024*1024)){
      ruleForm.value.coverUrl = ""
      imageUrl.value = ""
      isUploadImage.value = false
      return 
    }

    console.log(res, "文件上传成功")
    if(res[0]){
      isUploadImage.value = true
      ruleForm.value.coverUrl = res[0]
      /* 上传成功后清除校验 */
      ruleFormRef.value.clearValidate('coverUrl')
      /* 预览缩略图 */
      var reader = new FileReader()
      reader.onload = function(e) {
        imageUrl.value = e.target.result
      }
      reader.readAsDataURL(res[0])
    }
  })
}

/* 提交新增或编辑时，按钮禁用 */
const buttonLoading = ref(false)

/* 提交 */
const submitForm = (formName) => {
  ruleFormRef.value.validate((valid, fields) => {
    if(valid) {
      buttonLoading.value = true

      /* 新增时不传id */
      if(route.currentRoute.value.query.type == 'add'){
        delete ruleForm.value.id
      }

      /* 未更新图片时不传值 */
      if(!isUploadImage.value) {
        delete ruleForm.value.coverUrl
      }

      http.$POST("/PreachM/AddOrUpdatePreachTeamInfo", {...ruleForm.value}, { headers: { 'Content-Type': ContentTypeEnum.FORM_DATA } }).then(res => {
        buttonLoading.value = false
        if (res.IsError) {
          ElMessage.warning('操作失败');
        }else{
          ElMessage.success('操作成功');
          route.push({
            path: "/backend/publicize-city"
          })
        }
      }).catch(err => {
        buttonLoading.value = false
        ElMessage.warning('操作失败');
      })
    }else{
      ElMessage.warning('请先完成必填项');
    }
  })
}

/* 重置 */
const resetForm = (formName) => {
  ruleFormRef.value.resetFields()
  imageUrl.value = ""
  isUploadImage.value = false
}

/* 返回列表 */
const goList = () => {
  route.push({
    path: "/backend/publicize-city",
    query: route.currentRoute.value.query.currentPage ? { currentPage: route.currentRoute.value.query.currentPage } : {}
  })
}
</script>

<style lang='scss' scoped>
@import "@/assets/styles/backendElement.scss";
</style>